import httpx
import json
import asyncio
from PyCmpltrtok.common import md5, sep

PWD = 'my_password_001'


async def text_gen(xinput, xusername=''):
    xjson = dict()
    xjson['input'] = xinput
    xjson['check'] = md5(xinput + PWD + xusername)
    xjson['username'] = xusername

    async with httpx.AsyncClient() as client:
        delimiter = b'\0'
        async with client.stream(
            'POST',
            'http://127.0.0.1:7777/api',
            json=xjson
        ) as res:
            buffer = b''
            async for raw_chunk in res.aiter_raw():
                buffer += raw_chunk
                while (chunk_end := buffer.find(delimiter)) >= 0:
                    chunk, buffer = buffer[:chunk_end], buffer[chunk_end + 1:]
                    if not chunk:
                        continue
                    chunk = chunk.decode('utf8')
                    data = json.loads(chunk)
                    xouput = data['output']
                    yield xouput


if '__main__' == __name__:
    
    async def main():
        sep('1')
        x = '您好，请问今天天气如何？(Fastapi)'
        r = text_gen(x)
        async for text in r:
            print(text)

        sep('2')
        x = '请问顺义八维怎么走？(Fastapi)'
        r = text_gen(x)
        async for text in r:
            print(text)
    
    asyncio.run(main())
    